<?php
namespace app\server\controller;

use app\index\controller\Boot;
use swoole_process;
use swoole_websocket_server;
use think\Controller;

class Swoole extends Controller
{

    public $pid = 0; //主进程ID
    public $works = [];
    public $max_precess = 1;
    public $new_index = 0;

    //启动一个webSocket服务
    public function boot_run()
    {

        $server = new swoole_websocket_server("0.0.0.0", 9500);
        // swoole_set_process_name(sprintf('web_socket_php-ps:%s', 'master'));  //设置进程名称
        // echo posix_getpid(); //进程ID
        $server->set(array(
            'worker_num' => 1,
            'daemonize' => true,
            //'backlog' => 128,
        ));
        $server->on('open', function (swoole_websocket_server $server, $request) {
            echo "server: handshake success with fd{$request->fd}\n";
        });
        $server->on('message', function (swoole_websocket_server $server, $frame) {
            //客户端传递的数据
            $recive = json_decode($frame->data, true);
            if ($recive['type'] == 1) {
                $session_id = $recive['session_id'];
                //创建一个子进程处理vbot业务
                $process = new swoole_process(function (swoole_process $worker) use ($session_id) {
                    echo 'process ' . $session_id . ' is working ...' . PHP_EOL;
                    swoole_set_process_name(sprintf('php boot ps:%s', $session_id));
                    //执行微信机器人方法
                    $boot = new Boot($session_id, $worker->pid);
                    $boot->boot_run();
                });
                $pid = $process->start();
            }
          
            //信号监听子进程
            swoole_process::signal(SIGCHLD, function ($sig) {
                //必须为false，非阻塞模式
                while (1) {
                    $ret = swoole_process::wait(false);
                    if ($ret) {
                        //  echo "通讯信息: " . $process->read() . "\n";
                        echo json_encode($ret) . PHP_EOL;
                        echo "PID={$ret['pid']}\n";
                    } else {
                        echo 'break' . PHP_EOL;
                        break;
                    }
                }
            });
            // $data = json_decode($frame->data,true);
            // $server->push($frame->fd, "this is server");
        });
        $server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
        });
        $server->start();
    }

}
